<template>
  <div class="screenContent columnFlex">
    <div
      v-if="tabsActive=='screen'"
      class="carefulText rowFlex columnCenter"
    >
      <div class="icon">
        <i class="el-icon-warning"></i>
      </div>
      <span>进入页面后2-3s弹出，用户可手动关闭</span>
    </div>
    <el-form
      ref="ruleForm"
      :model="ruleForm"
      label-width="100px"
      label-position="top"
      class="demo-ruleForm"
    >
      <el-form-item prop="status">
        <span style="color:#606266;font-size: 14px;font-weight:500;margin-right:10px;">{{ tabItem.label }}</span> <el-switch
          v-model="ruleForm.status"
          :active-value="1"
          :inactive-value="2"
        ></el-switch>
      </el-form-item>
      <!-- 激励广告 -->
      <div v-if="tabsActive=='incentive'">
        <el-form-item
          label="广告位ID"
          prop="ad_ids_text"
        >
          <el-input
            v-model="ruleForm.ad_ids_text"
            style="width:320px"
            placeholder="请输入广告位ID"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="选择启用广告合同剧"
          prop="status"
        >
          <template slot="label">
            <span>选择启用广告合同剧<el-tooltip
                class="item"
                effect="dark"
                placement="top"
              >
                <div
                  slot="content"
                  class="tooltipLine"
                >
                  只需设置合同剧即可，版本剧、马甲剧会同步合同剧设置
                </div>
                <i
                  class="el-icon-question"
                  style="margin-left:5px;color:#86909C;"
                ></i>
              </el-tooltip></span>
            <el-button
              key=""
              style="margin-left: 14px;"
              type="text"
              size="medium"
              @click="onRemoveAll"
            >清除</el-button>
          </template>
          <el-select
            ref="select"
            v-model="ruleForm.playlet_ids"
            style="width: 935px;"
            filterable
            multiple
            remote
            placeholder="请输入关键词"
            :remote-method="remoteMethod"
            size="small"
            value-key="value"
            @change="onAdPlayletIds"
          >
            <el-option
              v-for="(item,index) in mainPlayletList"
              :key="item.value"
              :label="item.label"
              :value="item"
            > </el-option>
          </el-select>
        </el-form-item>
      </div>
      <el-form-item
        v-else
        prop="ad_ids_list"
      >
        <p class="userText">显示位置</p>
        <div class="boxPosition">
          <el-checkbox-group v-model="ruleForm.ad_ids_list">
            <el-checkbox
              v-for="(item,index) in boxPositionList"
              :key="index"
              :label="item"
            >{{ item.label }} <el-popover
                v-if="tabsActive=='banner'"
                placement="right"
                trigger="hover"
              >
                <div>
                  <el-image
                    style="width:240px;padding:0;"
                    :src=" `https://wanxiaomeng-1255977238.cos.ap-shanghai.myqcloud.com/mxy/web/image/${item.value}.png`"
                    class="qrImage"
                  ></el-image>
                </div>
                <i
                  slot="reference"
                  class="el-icon-question"
                  style="cursor: pointer; width: 16px !important;"
                ></i>
              </el-popover>
            </el-checkbox>
          </el-checkbox-group>
          <div
            v-if="ruleForm.ad_ids_list.length>0"
            class="table"
          >
            <BiTable
              :data="ruleForm.ad_ids_list"
              size="medium"
              :column="tableColums"
              fixed="sticky"
              fixed-offset="50"
              layout="total, prev, pager, next"
              :auto-scroll="false"
            >
              <template v-slot:id="{ row }">
                <el-input
                  v-model="row.id"
                  placeholder="请输入广告位ID"
                  clearable
                ></el-input>
              </template>
            </BiTable>
          </div>
        </div>
      </el-form-item>
      <filterUser :rule-form="ruleForm" />
    </el-form>
    <span class="dialog-footer">
      <!-- <el-button
        class="btn"
      >取 消</el-button> -->
      <el-button
        class="btn"
        type="primary"
        :loading="loading"
        @click="submitForm"
      >确 定</el-button>
    </span>
  </div>
</template>
<script>
import filterUser from './filterUser'
import { adverIndex, adverSave } from '@/api/adver'
import { mapState } from 'vuex'
import { commonData } from '@/api/common'
import { removeDp } from '@/utils/index'
export default {
  components: {
    filterUser
  },
  props: {
    tabsActive: {
      type: String,
      default: ''
    },
    tabItem: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      mainPlayletList: [],
      checkPlayletList: [],
      loading: false,
      isSuccess: true,
      ruleForm: {
        type: '',
        status: '',
        ad_ids: {},
        ad_ids_text: '',
        ad_ids_list: [],
        playlet_ids: [],
        playlet_ids_name: [],
        condition_operation: '',
        member_attribute: {
          operation: 1, // 当前版本只有1（且）
          condition: [
            // {
            //   type: 'seq_time',
            //   time_type: 1,
            //   start: 1,
            //   end: 2,
            //   unit: 1,
            //   range: 1,
            //   status: -1
            // }
          ]
        }, // 用户行为
        member_action: {
          operation: 1,
          condition: [
            // {
            //   type: 'cancel_pay',
            //   operation: 1,
            //   num_type: 1,
            //   num: 1
            // }
          ]
        },
        creator: ''
      },
      boxPositionList: [
        { label: '追剧页', value: 'zhuijv', id: '', type: 1 },
        { label: '剧场页', value: 'jvchang', id: '', type: 2 },
        { label: '福利页', value: 'fuli', id: '', type: 3 },
        { label: '我的页', value: 'my', id: '', type: 4 }
      ],
      tableColums: [
        {
          label: '显示位置',
          prop: 'label',
          width: 168
        },
        {
          label: '广告位ID',
          prop: 'id',
          renderHeader: (h, { row }) => {
            return (
              <div>
                广告位ID
                <el-tooltip class='item' effect='dark' placement='top'>
                  <div slot='content' class='tooltipLine'>
                    {this.routerItem.app_type != 2 ? <p style='width:260px;'>登录微信小程序后台，流量主栏位下，找到对应的广告栏位下，广告id进行填写</p> : <p style='width:260px;'>登录抖音小程序开放平台，运营-商业化变现下，找到对应的广告栏位下，广告id进行填写</p>}
                  </div>
                  <i class='el-icon-question' style='margin-left:5px;color:#86909C;'></i>
                </el-tooltip>
              </div>
            )
          },
          width: 330,
          slotScope: true
        }
      ],
      tableData: []
    }
  },
  computed: {
    ...mapState('user', ['userInfo', 'routerItem'])
  },
  async mounted() {
    await this.adverSet()
    await this.initMainPlayletList('')
  },
  methods: {
    onRemoveAll() {
      this.ruleForm.playlet_ids = []
    },
    onAdPlayletIds(value) {
      console.log(value)
      const index = value.findIndex((item) => {
        return item.value == '-1'
      })
      if (index != -1) {
        this.ruleForm.playlet_ids = JSON.parse(JSON.stringify(this.mainPlayletList))
        const index = this.mainPlayletList.findIndex((item) => {
          return item.value == '-1'
        })
        this.ruleForm.playlet_ids.splice(index, 1)
      }
    },
    mobileClear(async) {
      this.$nextTick(() => {
        if (!async) {
          // ios 手机有延迟问题
          setTimeout(() => {
            const { select } = this.$refs
            const input = select.$el.querySelector('.el-input__inner')
            input.removeAttribute('readonly')
          }, 200)
        }
      })
    },
    async remoteMethod(query) {
      if (!query) {
        return
      }
      const res = await commonData({
        type: 'mainPlayletDown',
        value: query,
        show_all: 1
      })
      if (res.status_code === 1) {
        console.log(this.ruleForm.playlet_ids, res.data.data)
        const map = new Map()
        for (const item of [...JSON.parse(JSON.stringify(res.data.data)), ...JSON.parse(JSON.stringify(this.ruleForm.playlet_ids))]) {
          if (!map.has(item.value)) {
            map.set(item.value, item)
          }
        }
        this.mainPlayletList = [...map.values()]
        this.mainPlayletList.unshift({ label: '全部', value: '-1' })
      }
    },
    async initMainPlayletList() {
      const res = await commonData({
        type: 'mainPlayletDown',
        value: '',
        show_all: 1
      })
      if (res.status_code === 1) {
        console.log(this.ruleForm.playlet_ids, res.data.data)
        const map = new Map()
        for (const item of [...JSON.parse(JSON.stringify(this.ruleForm.playlet_ids)), ...JSON.parse(JSON.stringify(res.data.data))]) {
          if (!map.has(item.value)) {
            map.set(item.value, item)
          }
        }
        this.mainPlayletList = [...map.values()]
        this.mainPlayletList.unshift({ label: '全部', value: '-1' })
      }
    },
    async adverSet() {
      try {
        const res = await adverIndex({ type: this.tabItem.type })
        if (res.status_code == 1) {
          if (res.data && res.data.status) {
            const data = res.data
            data.status = Number(res.data.status)
            if (this.tabsActive == 'incentive') {
              data.ad_ids_text = data.ad_ids[2]
              if (data.playlet_ids && data.playlet_ids.length > 0) {
                if (data.playlet_ids_name) {
                  this.mainPlayletList = data.playlet_ids_name.map((item) => {
                    return {
                      value: item.value * 1,
                      label: item.label
                    }
                  })
                  this.mainPlayletList.unshift({ label: '全部', value: '-1' })
                }
              }
            } else {
              data.ad_ids_list = []
              const list = []
              for (const key in data.ad_ids) {
                const itemId = this.boxPositionList.find((item) => item.type == key)
                itemId.id = data.ad_ids[key]
                list.push(itemId)
              }
              list.length > 0 ? (data.ad_ids_list = list) : ''
            }
            if (data.member_attribute?.condition && data.member_attribute.condition.length > 0) {
              data.member_attribute.condition = data.member_attribute.condition.map((item) => {
                let newItem = item
                if (newItem.type === 'seq_time') {
                  newItem.status = -1
                  newItem = {
                    type: newItem.type,
                    status: newItem.status,
                    time_type: newItem.time_type,
                    start: newItem.start,
                    end: newItem.end,
                    unit: newItem.unit,
                    range: newItem.range
                  }
                } else if (item.type === 'pay_status') {
                  newItem = {
                    type: item.type,
                    time_type: 1,
                    start: 1,
                    end: 1,
                    unit: 1,
                    range: 1,
                    status: item.status
                  }
                }
                return newItem
              })
            } else {
              // 暂时隐藏
              data.member_attribute = {
                operation: 1, // 当前版本只有1（且）
                condition: [
                  // {
                  //   type: 'seq_time',
                  //   time_type: 1,
                  //   start: 1,
                  //   end: 2,
                  //   unit: 1,
                  //   range: 1,
                  //   status: -1
                  // }
                ]
              }
            }
            if (!data.member_action || !data.member_action.condition || data.member_action.condition.length === 0) {
              data.member_action = {
                operation: 1,
                condition: [
                  // {
                  //   type: 'cancel_pay',
                  //   operation: 1,
                  //   num_type: 1,
                  //   num: 1
                  // }
                ]
              }
            }
            this.ruleForm = data
            this.ruleForm.playlet_ids = data.playlet_ids_name.map((item) => {
              return {
                value: item.value * 1,
                label: item.label
              }
            })
            console.log(this.ruleForm.playlet_ids)
          }
        }
      } catch (error) {}
    },
    handleForm() {
      const data = JSON.parse(JSON.stringify(this.ruleForm))
      data.type = this.tabItem.type
      data.creator = this.userInfo.username
      if (this.tabsActive == 'incentive') {
        data.ad_ids = {
          2: data.ad_ids_text
        }
        delete data.ad_ids_text
      } else {
        if (data.ad_ids_list && data.ad_ids_list.length > 0) {
          const noId = data.ad_ids_list.find((item) => item.id == '')
          if (noId) {
            this.$message.warning('请输入广告位ID')
            this.isSuccess = false
          }
        }
        const ad_ids = {}
        data.ad_ids_list.map((item) => {
          ad_ids[item.type] = item.id
        })
        data.ad_ids = ad_ids
        delete data.ad_ids_list
        delete data.ad_ids_text
      }
      if (data.member_attribute.condition && data.member_attribute.condition.length > 0) {
        data.member_attribute.condition.map((item) => {
          if (item.type === 'seq_time') {
            if (item.start >= item.end) {
              this.$message.close()
              this.$message.warning('开始时间不能大于等于结束时间')
              this.isSuccess = false
              return
            }
            this.$message.close()
            if (((!item.start && item.start !== 0) || (!item.end && item.end !== 0)) && item.type === 'seq_time') {
              this.$message.close()
              this.$message.warning('请输入数字')
              this.isSuccess = false
              return
            }
            delete item.status
          } else if (item.type === 'pay_status') {
            delete item.end
            delete item.start
            delete item.range
            delete item.time_type
            delete item.unit
          } else {
          }
          if (!this.isSuccess) {
            this.$message.close()
            return
          }
        })
      }
      if (data.member_action.condition && data.member_action.condition.length > 0 && this.isSuccess) {
        const noNum = data.member_action.condition.find((item) => !item.num && item.num !== 0)
        if (noNum) {
          this.$message.close()
          this.$message.warning('请输入次数')
          this.isSuccess = false
          return
        }
      }
      console.log(data.playlet_ids)
      data.playlet_ids = data.playlet_ids.map((item) => {
        console.log(item)
        return item.value
      })
      return data
    },
    submitForm() {
      this.isSuccess = true
      const formData = this.handleForm()
      if (!this.isSuccess) {
        // 校验失败
        return
      }
      this.adverSave(formData)
    },
    // 保存数据
    async adverSave(data) {
      this.loading = true
      try {
        const res = await adverSave(data)
        this.loading = false
        if (res.status_code == 1) {
          this.$message.success(res.msg)
        }
      } catch (error) {
        this.loading = false
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.screenContent {
  width: 100%;
  height: calc(100vh - 205px);
  padding-bottom: 80px;
  overflow-y: auto;
  .userText {
    font-size: 16px;
    font-family: PingFangSC, PingFang SC;
    font-weight: 500;
    color: #1d2129;
    flex-shrink: 0;
  }
  .carefulText {
    width: 100%;
    height: 40px;
  }

  .table {
    width: 500px;
  }
  .demo-ruleForm {
    ::v-deep .el-form-item--small.el-form-item {
      margin-bottom: 12px;
    }
  }
  .dialog-footer {
    background: #fff;
    z-index: 10;
    height: auto;
    padding-bottom: 20px;
    border-top: none;
  }
  .boxPosition {
    .table {
      margin-top: 5px;
      ::v-deep .el-table {
        border: 1px solid #dfe6ec;
        border-bottom: none;
        border-radius: 3px;
      }
      ::v-deep .el-table__header .cell {
        color: #1d2129;
        font-weight: 500;
      }
    }
  }
  ::v-deep .el-form-item__label {
    font-weight: 600;
    color: #1d2129;
  }
}
</style>